package com.yutons.encrypt.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title 国密算法加密偏移向量和密码
 * @Author yutons
 * @Date 2024-11-20 10:23
 * @Desc
 */
@Getter
@Setter
@ConfigurationProperties(MpEncryptProperties.PREFIX)
public class MpEncryptProperties implements Serializable {
	/**
	 * 配置属性的前缀，用于从配置文件中读取相关参数。
	 */
	public static final String PREFIX = "yutons.db.crypto";
	/**
	 * 启用动态密钥双向校验
	 * <p>
	 * 默认值：true
	 * </p>
	 */
	private Boolean enabled = Boolean.FALSE;
	public String primary;
	public List<SecretKey> secretKeys;

	private List<FieldObject> fields = new ArrayList<>();

	@Data
	public static class FieldObject {
		private String name;
		private String key;
	}

	@Data
	public static class SecretKey {
		/**
		 * 秘钥KEY
		 */
		public String key;
		/**
		 * 秘钥IV
		 */
		public String iv;
	}

	public MpEncryptProperties.SecretKey getSecretKey(String clazzName, String propertyName) {
		List<MpEncryptProperties.FieldObject> fields = this.fields;
		for (MpEncryptProperties.FieldObject field : fields) {
			String name = field.getName();
			String key = field.getKey();
			String[] names = name.split("::");
			if (clazzName.endsWith(names[0].contains(".") ? names[0] : "." + names[0]) && propertyName.equals(names[1])) {
				SecretKey secretKey = new SecretKey();
				secretKey.setKey(StrUtil.isEmpty(key) ? SecureUtil.md5(secretKeys.get(0).key).substring(2,18) : key);
				secretKey.setIv(SecureUtil.md5(secretKeys.get(0).key).substring(0,16));
				return secretKey;
			}
		}
		return null;
	}
}
